package com.cooksys.film_rental.bo.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cooksys.film_rental.bo.AddressBo;
import com.cooksys.film_rental.dao.AddressDao;
import com.cooksys.film_rental.model.Address;
import com.cooksys.film_rental.model.City;
import com.cooksys.film_rental.model.Country;
import com.cooksys.film_rental.model.Customer;
import com.cooksys.film_rental.model.Staff;
import com.cooksys.film_rental.model.Store;

@Service("AddressBo")
public class AddressBoImpl implements AddressBo {

	@Autowired(required = true)
	AddressDao addressDao;

	@Override
	public Address save(Address address) {
		return this.addressDao.save(address);

	}

	@Override
	public void update(Address address) {
		this.addressDao.update(address);

	}

	@Override
	public void delete(Address address) {
		this.addressDao.delete(address);

	}

	@Override
	public Address getAddressByAddressId(Short addressId) {
		return this.addressDao.getAddressByAddressId(addressId);
	}

	@Override
	public Address getAddressByAddressId(String addressId) {
		try {

			Short addressIdAsShort = Short.valueOf(addressId);
			return this.getAddressByAddressId(addressIdAsShort);

		} catch (NumberFormatException e) {

			System.err
					.println("Could not parse Short value for addressId from string: "
							+ addressId);
			e.printStackTrace();
			System.err.println("Returning null value...");
			return null;

		}

	}

	@Override
	public List<Address> searchAddressesByCity(City city) {
		return this.addressDao.searchAddressesByCity(city);
	}

	@Override
	public List<Address> searchAddressesByCountry(Country country) {
		return this.addressDao.searchAddressesByCountry(country);
	}

	@Override
	public Address getAddressByStore(Store store) {
		return this.addressDao.getAddressByStore(store);
	}

	@Override
	public Address getAddressByStaff(Staff staff) {
		return this.addressDao.getAddressByStaff(staff);
	}

	@Override
	public Address getAddressByCustomer(Customer customer) {
		return this.addressDao.getAddressByCustomer(customer);
	}

	@Override
	public void saveOrUpdate(Address address) {
		this.addressDao.saveOrUpdate(address);

	}

	@Override
	public Address matchAddressToDatabase(Address address, City city) {

		Address result = null;

		if (address.getAddressId() != null) {

			result = this.getAddressByAddressId(address.getAddressId());

		}

		if (result == null) {

			result = this.addressDao.getAddressByInfoAndCity(address.getAddress(),
					address.getAddress2(), address.getDistrict(),
					address.getPhone(), address.getPostalCode(), city);

		}

		return result;

	}

}
